const Database=require('better-sqlite3')
const path=require('path')
const db=new Database(path.join(__dirname,'app.db'))

function getAllTasks(user_id) {
  try{
    const rows=db.prepare('select * from tasks where user_id=?').all(user_id)
    return {status:1,message:'ok',data:rows};
  }catch(err){
    return {status:0,message:err.message};
  }
}

function addTasks(text,user_id) {
  try{  
    db.prepare('insert into tasks (text,user_id) values (?,?)').run(text,user_id);
    return {status:1,message:'ok'};
  }catch(err){
    return {status:0,message:err.message};
    }
}

function removeTaskById(id) {
  try{
    db.prepare('delete from tasks where id = ?').run(id);
    return {status:1,message:'ok'};
  }catch(err){
    return {status:0,message:err.message};
  }
}

function updateTaskById(text,id) {
  try{
    db.prepare('update tasks set text = ? where id = ?').run(text, id);
    return {status:1,message:'ok'};
  }catch(err){
    return {status:0,message:err.message};
  }
}

function deleteAllTasks(user_id) {
  try{
    db.prepare('delete from tasks where user_id=?').run(user_id);
    return {status:1,message:'ok'};
  }catch(err){
    return {status:0,message:err.message};
  }
}

module.exports = {
  getAllTasks,
  addTasks,
  removeTaskById,
  updateTaskById,
  deleteAllTasks
};
